package net.youpo.Market.UI.Manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.youpo.Market.BaseActivity;
import net.youpo.Market.MarketApplication;
import net.youpo.Market.R;
import net.youpo.Market.Bean.AppInfoBean;
import net.youpo.Market.Download.Downloads;
import net.youpo.Market.Net.HttpConnection;
import net.youpo.Market.UI.MainActivity;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.Util.DeviceInfo;
import net.youpo.Market.Util.GlobalVariables;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ExpandableListView;

public class AppManagerActivity extends BaseActivity {
	private final String REQS_CONFIG = "Apps/CheckVersion";
	private ProgressDialog mLoadingDialog;
	private ArrayList<AppInfoBean> mInstalledAppList, mNeedUpdateApplist;
	private final int LOADING_DONE = 0;
	private ExpandableListView mListView;
	private Cursor mUpdatingCursor;
	protected Map<Integer, Cursor> cursorMap = new HashMap<Integer, Cursor>();
	private AppManagerAdapter mAdapter;
	private boolean flag = false;
	private PackageReceiver mReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appmanager_layout);
		init();
		registerReceiver();
	}

	/*
	 * 请求地址
	 * http://youpo.vicp.net:1086/Market/Apps/CheckVersion?vc=版本号（VersionCode数字
	 * ）&imei=IMEI码&packages=包名:数字版本号; 包名:数字版本号 参数说明 Post协议 返回值 {“sc”:200, uds:[
	 * {“id”:”应用ID”,“pn”:”应用包名称”,”dl”:”下载地址”} …. ] } 状态码 作用 200 请求已处理，有返回值 204
	 * 请求己处理，无返回值 400 无效的请求 500 服务器处理出错
	 */

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
		dissmissProgressDialog();
	}

	private void init() {
		mListView = (ExpandableListView) findViewById(R.id.list);
		mLoadingDialog = ProgressDialog.show(getParent(), "", "正在加载. 请等待...",
				true);
		mUpdatingCursor = managedQuery(Downloads.Impl.CONTENT_URI,
				new String[] { Downloads.Impl._ID, Downloads.Impl.COLUMN_TITLE,
						Downloads.Impl.COLUMN_STATUS,
						Downloads.Impl.COLUMN_TOTAL_BYTES,
						Downloads.Impl.COLUMN_CURRENT_BYTES,
						Downloads.Impl.COLUMN_DESCRIPTION,
						Downloads.Impl.COLUMN_APP_ID,
						Downloads.Impl.COLUMN_ICON_URL,
						Downloads.Impl.COLUMN_PACKAGE_NAME,
						Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
						Downloads.Impl.COLUMN_LAST_MODIFICATION,
						Downloads.Impl.COLUMN_VISIBILITY, Downloads.Impl._DATA,
						Downloads.Impl.COLUMN_MIME_TYPE,
						Downloads.Impl.COLUMN_CONTROL },
				Downloads.Impl.COLUMN_DOWNLOAD_TYPE + " = ?",
				new String[] { String.valueOf(Downloads.TYPE_UPDATE) },
				Downloads.Impl._ID);
		new Thread(new Runnable() {
			@Override
			public void run() {
				mInstalledAppList = DeviceInfo.getInstallAppInfo();
				StringBuffer sb = new StringBuffer();
				sb.append("vc=" + ConstantsTable.NOW_VERSION + "&imei="
						+ ConstantsTable.IMEI + "&packages=");
				for (AppInfoBean appinfo : mInstalledAppList) {
					sb.append(appinfo.APP_PACK + ":" + appinfo.APP_VER + ";");
				}
				Log.e("resultJson", sb.toString());
				HttpConnection hc = new HttpConnection();
				String resultJson = hc.requestService2(REQS_CONFIG, sb);
				Log.e("resultJson", "result:" + resultJson);
				getJsonData(resultJson);
				mHandler.sendEmptyMessage(LOADING_DONE);// 加载完成
			}
		}).start();

	}

	private void getJsonData(String json) {
		mNeedUpdateApplist = new ArrayList<AppInfoBean>();
		JSONObject jsonObject;
		PackageManager pm = MarketApplication.getMarketAppContext()
				.getPackageManager();
		try {
			jsonObject = new JSONObject(json);
			JSONArray jsonArray = jsonObject.getJSONArray("uds");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
				AppInfoBean mAppBean = new AppInfoBean();
				mAppBean.APP_ID = jsonObject2.getString("id");
				mAppBean.APP_PACK = jsonObject2.getString("pn");
				mAppBean.APP_URL = jsonObject2.getString("dl");
				PackageInfo packageInfo = pm.getPackageInfo(mAppBean.APP_PACK,
						0);
				mAppBean.APP_NAME = packageInfo.applicationInfo.loadLabel(pm)
						.toString();
				mAppBean.APP_ICON_BMP = packageInfo.applicationInfo
						.loadIcon(pm);
				mAppBean.APP_VER = packageInfo.versionCode;
				mNeedUpdateApplist.add(mAppBean);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mAdapter == null) {
			flag = true;
		} else {
			mAdapter.registerContentObserver();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mAdapter != null)
			mAdapter.unregisterContentObserver();
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case LOADING_DONE: {
				if (mNeedUpdateApplist.isEmpty()) {
					MainActivity.setTabNum(
							String.valueOf(mNeedUpdateApplist.size()), false);
				} else {
					MainActivity.setTabNum(
							String.valueOf(mNeedUpdateApplist.size()), true);
				}
				mAdapter = new AppManagerAdapter(AppManagerActivity.this,
						mUpdatingCursor, mNeedUpdateApplist, mInstalledAppList,
						mListView);
				if (flag == true) {
					mAdapter.registerContentObserver();
				}
				mListView.setAdapter(mAdapter);
				mListView.setGroupIndicator(null);
				mListView.expandGroup(AppManagerAdapter.GROUP_ID_UPDATING);
				mListView.expandGroup(AppManagerAdapter.GROUP_ID_NEED_UPDATE);
				mListView.expandGroup(AppManagerAdapter.GROUP_ID_INSTALLED);
				dissmissProgressDialog();
				break;
			}
			default:
			}

		}
	};

	public class PackageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 接收广播：设备上删除了一个应用程序包。
			if (intent.getAction().equals(
					"android.intent.action.PACKAGE_REMOVED")) {
				String packageName = intent.getDataString();
				Log.e(ConstantsTable.LOG_TAG, "卸载了:" + packageName + "包名的程序");
				new Thread(new Runnable() {
					@Override
					public void run() {
						mInstalledAppList = DeviceInfo.getInstallAppInfo();
						mAdapter.setInstalledList(mInstalledAppList);
						mAdapter.refreshInstalledData();
						AppManagerActivity.this.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mListView
										.collapseGroup(AppManagerAdapter.GROUP_ID_INSTALLED);
								mListView
										.expandGroup(AppManagerAdapter.GROUP_ID_INSTALLED);
							}
						});

					}
				}).start();
			}
			if (intent.getAction()
					.equals("android.intent.action.PACKAGE_ADDED")) {
				String packageName = intent.getDataString();
				packageName = packageName.replace("package:", "");
				Log.e(ConstantsTable.LOG_TAG, "安装了:" + packageName + "包名的程序");
				String where = Downloads.Impl.COLUMN_PACKAGE_NAME + " = ? AND "
						+ Downloads.Impl.COLUMN_STATUS + " = ? AND "
						+ Downloads.Impl.COLUMN_DOWNLOAD_TYPE + " = ?";
				getContentResolver().delete(
						Downloads.Impl.CONTENT_URI,
						where,
						new String[] { packageName,
								String.valueOf(Downloads.STATUS_SUCCESS),
								String.valueOf(Downloads.TYPE_UPDATE) });
				new Thread(new Runnable() {
					@Override
					public void run() {
						AppManagerActivity.this.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mAdapter.refreshData();
								mListView
										.collapseGroup(AppManagerAdapter.GROUP_ID_UPDATING);
								mListView
										.expandGroup(AppManagerAdapter.GROUP_ID_UPDATING);
								mInstalledAppList = DeviceInfo.getInstallAppInfo();
								mHandler.sendEmptyMessage(LOADING_DONE);
							}
						});

					}
				}).start();
			}

		}
	}

	private void registerReceiver() {
		mReceiver = new PackageReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("android.intent.action.PACKAGE_REMOVED");
		intentFilter.addAction("android.intent.action.PACKAGE_ADDED");
		intentFilter.addDataScheme("package");
		registerReceiver(mReceiver, intentFilter);
	}

	private void dissmissProgressDialog() {
		if (mLoadingDialog != null && !isFinishing()
				&& mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}

}
